<html>
<head>
  <script src="jquery.js"></script>
  <script src="icon.js"></script>
  <script src="storage.js"></script>
  <script>
  var alerts = new Array();
  var list;
  chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
  chrome.browserAction.setBadgeText({text:"?"});

  var friends = 0;
  var friendsOnline = 0;
  var unread = 0;

  var waitingForList = false;
  var friendsList = "";
  var msgList = "";

  var loggingIn = false;
  var loginAttempt = 0;

  var t;

  var locale = chrome.i18n.getMessage; // Short-hand
   
  // Message passing
  chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    switch(request.type){
        case "friendsList":
            if(friendsList == "" || msgList == ""){
                waitingForList = true;
                sendResponse({ok:false});
            }
            else if(request.now){
                waitingForList = true;
                sendResponse({ok:false});
                clearTimeout(t);
                update();
            }
            else{
              sendResponse(
                {
                    ok:true,
                    list: friendsList,
                    msgList:msgList,
                });
            }
            break;

        case "refreshStorage":
            loadSettings();
            sendResponse({ok:true});
            break;
        default:
            sendResponse({}); // snub them.
            break;
     }
  });

  
  //READY
  $(document).ready(function (){
     
      loadSettings();

      t = setTimeout("update();", 5000);
      icon = document.getElementById("canvas");
      loadCanvas();
      chrome.browserAction.setIcon({imageData:icon.ImageData});
      
  });

  //Main update function
  function update(){
      clearTimeout(t);
      if(loggingIn)
        return;
      chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
      chrome.browserAction.setBadgeText({text:"."});
      // ---------- LOAD FRIENDLIST --------------
      $("#drop").load("http://live.xbox.com/profile/Friends.aspx #ctl00__shellFlare", function(){

          //Check if logged in
          if($(".XbcTableFriendOnline, .XbcTableFriendOffline").length.toString() != "0"){
            //Build friendslist
            friendsList = "";
            $(".XbcTableFriendOnline, .XbcTableFriendOffline").each(function (){
                  
                  var str = "<tr class='" + $(this).attr("class") + "'>";
                  str += "<td title='" + $.trim($(this).children(".XbcGamerPresence").text()) + "'>" + $(this).children(".XbcGamerTag").html() + "</td>";

                  var desc = $(this).children(".XbcGamerDescription").html();
                  var desc2;
                  if(desc.indexOf("<br>") > 0){
                     desc2 = desc.split("<br>")[1].trim();
                     desc = desc.split("<br>")[0].trim();
                     if(desc2.length > 0)
                        desc2 = "onmouseover=\"onlineOver(this);\" onmouseout=\"onlineOut(this);\" title='" + desc2 + "'";
                  }
                  str += "<td " + desc2 + ">" + desc + "</td>";
                  str += "</tr>";
                  friendsList += str;
                  
              });


            //Number of friends
            var temp = $(".XbcFriendsHeaderLeftPanel").children("h1").html();
            friends = parseInt(temp.substring(temp.indexOf("(")+1, temp.indexOf(")")));
            temp =    $(".XbcFriendsHeaderLeftPanel").children("h2").html();
            friendsOnline = parseInt(temp.substring(temp.indexOf("(")+1, temp.indexOf(")")));
            chrome.browserAction.setBadgeText({text:".."});
            
            //Unread messages
            temp = $("#ctl00__subheaderControl_messagesLink").html();
            if(temp.indexOf("(") <= 0)
              unread = 0;
            else
            {
              unread = parseInt(temp.substring(temp.indexOf("(")+1, temp.indexOf(")")));
            }
            

            updateMsg();
          }
          else{
            //If logged out
            
            if(settings["autologin"].value == "true"){
               loginAttempt++;
               if(loginAttempt <= 3){
                 friendsList = "<tr><th colspan='2'>" + locale("auto_attempt") + " " + loginAttempt + "</img></th></tr>" 
                            +"<tr><th colspan='2'><img src='ajax-loader.gif'></img></th></tr>"
                 var al = setTimeout("autoLogin();", 100);
               }
               else{
                 friendsList = "<tr><th colspan='2'>" + locale("auto_fail") + "</<th></tr>"
                        + "<tr><th colspan='2'><a href='http://live.xbox.com/'>" + locale("man_click") + "</a></th></tr>"
                        + "<tr><th colspan='2'><button onclick='requestList(true);'>" + locale("man_refresh") +  "</button></th></tr>";
                 loginAttempt = 0;
               }
            }
            else{
              friendsList = "<tr><th colspan='2'>" + locale("not_logged_in") + "</<th></tr>"
                        + "<tr><th colspan='2'><a href='http://live.xbox.com/'>" + locale("man_click") + "</a></th></tr>"
                        + "<tr><th colspan='2'><button onclick='requestList(true);'>" + locale("man_refresh") +  "</button></th></tr>";
            }
            friends = friendsOnline = unread = -1;
            msgList = friendsList;
            completeUpdate();
          }
          

      });

      t=setTimeout("update();", settings["interval"].value*1000);      
  }
  function updateMsg(){
    $("#dropMsg").load("http://live.xbox.com/profile/MessageCenter/ViewMessages.aspx .XbcProfileTableContainer", function(){
        var d = $("#dropMsg");
        msgList = "";
        d.find(".XbcMessageRead, .XbcMessageUnread").each(function(){
            var msgId = $(this).find("a").attr("href");
            msgId = msgId.substring(msgId.indexOf("?mx=") + 4, msgId.length);
            var gt = $(this).find("a").text();
            var text = $(this).find(".XbcMessageListSubject").text();
            msgList += ("<tr class='" + $(this).attr("class") + "'>" + 
                            "<td class='expandMsg'>" + 
                                "<a href='javascript:;' onclick=\"openMsg('" + msgId + "', this);\">" + 
                                    "<img src='plus.png' />" + 
                                "</a>" +
                            "</td>" +
                            "<td>" + gt + "<span class='loadingMsg'><img src='ajax-loader-kit.gif'></img></span></td>" +
                            "<td>" + text + "</td></a>" +
                        "</tr>");
            msgList += ("<tr class='msgBody'></tr>");
        });
        msgList += "";
        
        completeUpdate();
    });
  }

  //Update/refresh UI and send list to popup
  function completeUpdate(){
    var temp = "F:" + friendsOnline.toString();
    if(unread > 0){
      chrome.browserAction.setBadgeBackgroundColor({color:[0, 240, 0, 255]});
      temp = "U:" + unread.toString();
    }
    else
      chrome.browserAction.setBadgeBackgroundColor({color:[50, 200, 0, 255]});

    if(friends == -1){
      chrome.browserAction.setBadgeText({text:"?"});
      chrome.browserAction.setBadgeBackgroundColor({color:[200, 200, 200, 255]});
      chrome.browserAction.setTitle({title:"Xbox LIVE Center"});
    }
    else{
      chrome.browserAction.setBadgeText({text:temp});
      chrome.browserAction.setTitle({title:
                        locale("friendsOnline") + ": " + friendsOnline + "/" + friends + "\r\n" +
                        locale("unreadMsgs") + ": " + unread});
    }
    
    // If popup is waiting
    if(waitingForList){
          waitingForList = false;
          chrome.extension.sendRequest(
          {
              type: "waitingList",
              list:friendsList,
              msgList:msgList,
          }
          , function(response) {
              console.log("WaitingList sent");
        });
    }
  }
  function autoLogin(){
    loggingIn = true;
    

   $("#alFrame")[0].onload = function() {contAL();};
   $("#alFrame")[0].src = "http://live.xbox.com/";

  }
  function contAL(){
    loggingIn = false;
    waitingForList = true;
    update();
  }
  </script>
</head>
<body>
<div id="drop" style="display:none;"></div>
<div id="dropMsg" style="display:none;"></div>
<canvas id="canvas" width="19" height="19"></canvas>
<iframe id="alFrame"></iframe>
</body>
</html>
